package han.cirno.corrupt.modules.login

import androidx.activity.compose.LocalActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.res.painterResource
import han.cirno.corrupt.compose.localeStringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import han.cirno.corrupt.R
import han.cirno.corrupt.activity.main.LocalNavController
import han.cirno.corrupt.activity.main.MainActivityViewModel
import han.cirno.corrupt.compose.SimpleRadioButton
import han.cirno.corrupt.compose.VerticalSpacer
import han.cirno.corrupt.data.instances.UserSchoolData
import han.cirno.corrupt.funny.LoginSurface

@Composable
fun LoginLayout(){
    val pageState = remember { mutableIntStateOf(0) }
    val schoolState = remember { mutableStateOf(UserSchoolData.School.None) }
    val pageVal by pageState
    val selectState = remember { mutableIntStateOf(
        when(schoolState.value){
            UserSchoolData.School.FAFU->0
            UserSchoolData.School.MJU->1
            UserSchoolData.School.FJUT->2
            else->0
        }) }
    val pageSchoolChoose = @Composable { PageSchoolChoose(pageState,schoolState,selectState) }
    val pageLogin = @Composable { PageLogin( pageState,schoolState) }
    Box (
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center){
        //It's too fancy, I'd rewrite it with Compose...
        //FancyBackgroundQwQ()
        Card(modifier = Modifier.padding(32.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)) {
            Column (modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()){
                AnimatedContent(pageVal) {p->
                    when(p) {
                        0 -> pageSchoolChoose()
                        1 -> pageLogin()
                    }
                }
            }
        }
    }
}

@Composable
fun PageLogin(
    pageState: MutableState<Int>,
    schoolState: MutableState<UserSchoolData.School>,
)= Box{
    val viewModel:MainActivityViewModel= hiltViewModel(LocalActivity.current as AppCompatActivity)
    val navController= LocalNavController.current
    @Suppress("SpellCheckingInspection") val passwordRandom="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+`~,./<>?;':[]{}\\|"
    val userNameState = remember { mutableStateOf("") }
    val passwordState = remember { mutableStateOf("") }
    val showPasswordState = remember { mutableStateOf(false) }
    val loggingState = viewModel.isLoggingState
    val loggingText =viewModel.loginLoadingTextState
    val visualTransformation =
        VisualTransformation {
            TransformedText(
                AnnotatedString(genFancyText(passwordRandom,it.length)),
                OffsetMapping.Identity)
        }
    val primaryColor=MaterialTheme.colorScheme.primary
    val tertiaryColor=MaterialTheme.colorScheme.tertiary
    val brush = remember { Brush.linearGradient(colors = listOf(primaryColor,tertiaryColor)) }
    var userName by userNameState
    var password by passwordState
    var showPassword by showPasswordState
    Row(
        modifier = Modifier.clickable(enabled = !loggingState.value) { pageState.value=0 },
        horizontalArrangement = Arrangement.Start,
        verticalAlignment = Alignment.CenterVertically) {
        Icon(
            painter = painterResource(R.drawable.baseline_arrow_back_24),
            contentDescription = null)
        Text(
            text = localeStringResource(R.string.login_back),
            color =if(!loggingState.value) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally) {
        VerticalSpacer(4.dp)
        Text(
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.titleLarge,
            text= localeStringResource(R.string.login_title))
        Text(
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.bodyMedium,
            text= localeStringResource(when(schoolState.value){
                UserSchoolData.School.FAFU->R.string.login_fafu_subtitle
                UserSchoolData.School.MJU->R.string.login_mju_subtitle
                UserSchoolData.School.FJUT->R.string.login_fjut_subtitle
                else->throw IllegalArgumentException("Not a valid school")
            }))
        VerticalSpacer(8.dp)
        Text(
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.bodyMedium,
            text= localeStringResource(when(schoolState.value){
                UserSchoolData.School.FAFU->R.string.login_fafu_warning
                UserSchoolData.School.MJU->R.string.login_mju_warning
                UserSchoolData.School.FJUT->R.string.login_fjut_warning
                else->throw IllegalArgumentException("Not a valid school")
            }))
        VerticalSpacer(8.dp)
        OutlinedTextField(
            enabled = !loggingState.value,
            value = userName,
            singleLine = true,
            modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp),
            onValueChange = {userName=it},
            label = { Text(
                text = localeStringResource(R.string.login_serial),
                style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace)) },
            textStyle = MaterialTheme.typography.bodyLarge.copy(brush=brush, fontFamily = FontFamily.Monospace),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Next))
        OutlinedTextField(
            enabled = !loggingState.value,
            value = password,
            visualTransformation = if (showPassword) VisualTransformation.None else visualTransformation,
            singleLine = true,
            modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp),
            onValueChange = {password=it},
            label = { Text(
                text = localeStringResource(R.string.login_password),
                style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace)) },
            textStyle = MaterialTheme.typography.bodyLarge.copy(brush=brush, fontFamily = FontFamily.Monospace),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
            trailingIcon = {
                Icon(
                    modifier = Modifier.clickable { showPassword=!showPassword },
                    painter = painterResource(
                    if(showPassword)R.drawable.baseline_visibility_24
                    else R.drawable.baseline_visibility_off_24),
                    contentDescription = null)
            })
        VerticalSpacer(24.dp)
        AnimatedVisibility(visible = loggingState.value) {
            LinearProgressIndicator()
        }
        AnimatedVisibility(visible = !loggingState.value) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Button(
                    modifier = Modifier.width(128.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = MaterialTheme.colorScheme.onPrimary
                    ),
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 4.dp,
                        pressedElevation = 0.dp
                    ),
                    onClick = {
                        viewModel.submitLogin(userName,password,schoolState.value){
                            navController.popBackStack()
                            viewModel.refresh()
                        }
                    }) {
                    Text(
                        text = localeStringResource(R.string.login_submit),
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
            }
        }
        Text(text = loggingText.value)
        VerticalSpacer(4.dp)
    }
}

@Composable
fun PageSchoolChoose(
    pageState: MutableState<Int>,
    schoolState: MutableState<UserSchoolData.School>,
    selectState:MutableState<Int>,
    )= Column(
    modifier = Modifier.fillMaxWidth(),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center){
    Text(
        textAlign = TextAlign.Center,
        style = MaterialTheme.typography.titleLarge,
        text= localeStringResource(R.string.login_title))
    Text(
        textAlign = TextAlign.Center,
        style = MaterialTheme.typography.bodyMedium,
        text= localeStringResource(R.string.login_choose_school))
    VerticalSpacer(8.dp)
    Column {
        SimpleRadioButton(R.string.school_fafu, 0, selectState)
        SimpleRadioButton(R.string.school_mju, 1, selectState)
        SimpleRadioButton(R.string.school_fjut, 2, selectState)
    }
    VerticalSpacer(8.dp)
    OutlinedButton (onClick = {
        pageState.value=1
        schoolState.value=when(selectState.value){
            0->UserSchoolData.School.FAFU
            1->UserSchoolData.School.MJU
            2->UserSchoolData.School.FJUT
            else->UserSchoolData.School.None
        }
    }) { Text(text= localeStringResource(R.string.submit)) }
}

fun genFancyText(content:String,length:Int):String{
    val stringBuilder=StringBuilder()
    for(i in 0 until length)
        stringBuilder.append(content.random())
    return stringBuilder.toString()
}

@Composable
fun FancyBackgroundQwQ(){
    AndroidView(factory = {
        LoginSurface(it)
    })
}